package org.example.userservice.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.example.Response.ApiResponse;
import org.example.Response.ApiResponseUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import com.fasterxml.jackson.databind.ObjectMapper;

@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice<Object> {


    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 检查返回类型的Content-Type
        // 如果是文件类型，则不拦截
        String contentType = returnType.getMethod().getReturnType().getName();

        // 文件类型：例如图片、视频、PDF等
        if (contentType.startsWith("application/") || contentType.startsWith("image/") || contentType.startsWith("video/")) {
            return false;  // 如果是文件类型，不拦截
        }

        return true;  // 否则拦截
    }

    @Override
    public Object beforeBodyWrite(
            Object body,
            MethodParameter returnType,
            MediaType selectedContentType,
            Class<? extends HttpMessageConverter<?>> selectedConverterType,
            ServerHttpRequest request,
            ServerHttpResponse response
    ) {
        // 如果已经是 ApiResponse 类型的响应，直接返回
        if (body instanceof ApiResponse) {
            return body;
        }

        // 如果是文件类型，不做任何处理
        String contentType = selectedContentType.toString();
        if (contentType.startsWith("application/") || contentType.startsWith("image/") || contentType.startsWith("video/")) {
            return body;  // 如果是文件类型，返回原始结果
        }

        if (returnType.getGenericParameterType().equals(String.class)) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                // 将数据包装在ResultVO里后，再转换为json字符串响应给前端
                return objectMapper.writeValueAsString(ApiResponse.success(body));
            } catch (JsonProcessingException e) {
                return ApiResponseUtil.error("返回String类型错误");
            }
        }
        return ApiResponse.success(body);  // 返回封装后的对象
    }
}